home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 60 / IOPROG_60.ISO / soft / c++ / gsl-1.1.1-setup.exe / {app} / src / rng / coveyou.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-12-02  |  2.2 KB  |  92 lines

  1. /* rng/coveyou.c
  2.  * 
  3.  * This program is free software; you can redistribute it and/or modify
  4.  * it under the terms of the GNU General Public License as published by
  5.  * the Free Software Foundation; either version 2 of the License, or (at
  6.  * your option) any later version.
  7.  * 
  8.  * This program is distributed in the hope that it will be useful, but
  9.  * WITHOUT ANY WARRANTY; without even the implied warranty of
  10.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  11.  * General Public License for more details.
  12.  * 
  13.  * You should have received a copy of the GNU General Public License
  14.  * along with this program; if not, write to the Free Software
  15.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16.  */
  17.  
  18. /*
  19.  * This generator is taken from
  20.  *
  21.  * Donald E. Knuth
  22.  * The Art of Computer Programming
  23.  * Volume 2
  24.  * Third Edition
  25.  * Addison-Wesley
  26.  * Section 3.2.2
  27.  *
  28.  * This implementation copyright (C) 2001 Carlo Perassi.
  29.  * I reorganized the code to use the rng framework of GSL.
  30.  */
  31.  
  32. #include <config.h>
  33. #include <stdlib.h>
  34. #include <gsl/gsl_rng.h>
  35.  
  36. #define MM 0xffffffffUL        /* 2 ^ 32 */
  37.  
  38. static inline unsigned long int ran_get (void *vstate);
  39. static double ran_get_double (void *vstate);
  40. static void ran_set (void *state, unsigned long int s);
  41.  
  42. typedef struct
  43. {
  44.   unsigned long int x;
  45. }
  46. ran_state_t;
  47.  
  48. static inline unsigned long int
  49. ran_get (void *vstate)
  50. {
  51.   ran_state_t *state = (ran_state_t *) vstate;
  52.  
  53.   state->x = (state->x * (state->x + 1)) & MM;
  54.  
  55.   return state->x;
  56. }
  57.  
  58. static double
  59. ran_get_double (void *vstate)
  60. {
  61.   ran_state_t *state = (ran_state_t *) vstate;
  62.  
  63.   return ran_get (state) / 4294967296.0;
  64. }
  65.  
  66. static void
  67. ran_set (void *vstate, unsigned long int s)
  68. {
  69.   ran_state_t *state = (ran_state_t *) vstate;
  70.  
  71.   unsigned long int diff = ((s % 4UL) - 2UL) % MM;
  72.  
  73.   if (diff)
  74.     state->x = (s - diff) & MM;
  75.   else
  76.     state->x = s & MM;
  77.  
  78.   return;
  79. }
  80.  
  81. static const gsl_rng_type ran_type = {
  82.   "coveyou",            /* name */
  83.   MM,                /* RAND_MAX */
  84.   0,                /* RAND_MIN */
  85.   sizeof (ran_state_t),
  86.   &ran_set,
  87.   &ran_get,
  88.   &ran_get_double
  89. };
  90.  
  91. const gsl_rng_type *gsl_rng_coveyou = &ran_type;
  92.